package com.example.state.machine.config;

import com.example.state.machine.enums.OrderEvent;
import com.example.state.machine.enums.OrderState;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.guard.Guard;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;

import java.math.BigDecimal;
import java.util.EnumSet;

/*
 * 状态机配置
 */
@Configuration
@EnableStateMachineFactory
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<OrderState, OrderEvent> {

    @Override
    public void configure(StateMachineConfigurationConfigurer<OrderState, OrderEvent> config) throws Exception {
        config
                .withConfiguration()
                .autoStartup(true)
                .listener(listener());
    }

    /**
     * 配置状态
     */
    @Override
    public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {
        states
                .withStates()
                .initial(OrderState.UNPAID)    // 初始状态
                .end(OrderState.COMPLETED)     // 终态：已确认
                .end(OrderState.CANCELLED)     // 终态：已取消
                .states(EnumSet.allOf(OrderState.class));
    }

    /**
     * 配置状态转换事件关系
     */
    @Override
    public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) throws Exception {
        transitions
                // 支付事件：UNPAID → PAID（需检查金额）
                .withExternal()
                    .source(OrderState.UNPAID).target(OrderState.PAID)
                    .event(OrderEvent.PAY)
                    .and()
                // 取消事件：UNPAID → CANCELLED
                .withExternal()
                    .source(OrderState.UNPAID).target(OrderState.CANCELLED)
                    .event(OrderEvent.CANCEL)
                    .and()
                // 发货事件：PAID → SHIPPED
                .withExternal()
                    .source(OrderState.PAID).target(OrderState.SHIPPED)
                    .event(OrderEvent.SHIP)
                    .and()
                // 确认收货事件：SHIPPED → COMPLETED
                .withExternal()
                    .source(OrderState.SHIPPED).target(OrderState.COMPLETED)
                    .event(OrderEvent.CONFIRM);
    }

    // 状态监听器
    @Bean
    public StateMachineListener<OrderState, OrderEvent> listener() {
        return new StateMachineListenerAdapter<>() {
            @Override
            public void stateChanged(State<OrderState, OrderEvent> from, State<OrderState, OrderEvent> to) {
                System.out.println("State change to " + to.getId());

            }
        };
    }

    // 守卫条件：支付金额必须大于0
    @Bean
    public Guard<OrderState, OrderEvent> paymentGuard() {
        return context -> {
            Order order = context.getMessage().getHeaders().get("order", Order.class);
            if (order != null) {
                return order.getAmount().compareTo(BigDecimal.ZERO) > 0;
            }
            return false;
        };
    }
}

// 参考官方文档 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#developing-your-first-spring-statemachine-application